<template>
  <div class="app-container">

    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="关键字" prop="keyword">
        <el-input v-model="queryParams.keyword" placeholder="请输入关键字"
          clearable size="small" style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-divider direction="vertical"></el-divider>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddTable" plain>新增</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="dataList">
      <el-table-column label="表单key" align="left" key="formDefKey" prop="formDefKey"/>
      <el-table-column label="表单名称" align="left" key="formDefName" prop="formDefName" :show-overflow-tooltip="true" />
      <el-table-column label="一对多" width="160" align="left" key="oneToMore" prop="oneToMore">
        <template slot-scope="scope">
          <span v-if="scope.row.oneToMore">是</span>
          <span v-else-if="!scope.row.oneToMore">否</span>
          <span v-else>异常</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="left" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="left"
        width="240"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改基本信息</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDesign(scope.row)"
          >预览</el-button>
          <el-button
            v-if="scope.row.userId !== 1"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="dialog.title" :visible.sync="dialog.open" width="750px" append-to-body>
      <el-form ref="dialog.form" :model="dialog.form" :rules="dialog.rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="表名称" prop="formDefName">
              <el-input v-model="dialog.form.formDefName" placeholder="请输入表名称" readonly="readonly"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="key" prop="formDefKey">
              <el-input v-model="dialog.form.formDefKey" placeholder="请输入key" readonly="readonly"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="一对多">
              <el-radio-group v-model="dialog.form.oneToMore" size="small">
                <el-radio-button label="true">是</el-radio-button>
                <el-radio-button label="false">否</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="dialog.form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="dialogAdd.title" :visible.sync="dialogAdd.open" width="750px" append-to-body>
      <el-transfer
        style="text-align: left; display: inline-block;"
        v-model="selected"
        filterable
        :titles="['表定义', '已选择']"
        :button-texts="['移除', '添加']"
        :props="{ key: 'formKey', label: 'formTitle' }"
        @change="handleChange"
        :data="formDefList">
        <span slot-scope="{ option }">{{ option.formTitle }}</span>
      </el-transfer>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancelAdd">确 定</el-button>
        <el-button @click="cancelAdd">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

    import {listDef} from "@/api/openform/generator";
    import {listRole} from "@/api/system/role";
    import {
        deleteUserTableSetting,
        getUserTableSettingByKey,
        getUserTableSettings,
        saveUserTableSetting,
        updateUserTableSetting
    } from "@/api/renshi/person/userTableSetting";

    export default {
        name: "User",
        data() {
            return {
                // 遮罩层
                loading: false,
                // 总条数
                total: 0,
                // 用户表格数据
                dataList: null,
                // 角色选项
                roleOptions: [],
                // 角色名称，用于搜索
                roleName: undefined,
                // 弹出层
                dialog: {
                    open: false,
                    form: {
                        formDefName: undefined,
                        roleKeys: undefined,
                        oneToMore: false,
                        remark: undefined,
                        formDefKey: undefined,
                    },
                    // 表单校验
                    rules: {
                        formDefName: [
                            { required: true, message: "表名称必填", trigger: "blur" }
                        ],
                        formDefKey: [
                            { required: true, message: "key必填", trigger: "blur" }
                        ],
                        roleKeys: [
                            { required: true, message: "至少选择一个角色", trigger: "blur" }
                        ]
                    }
                },
                formDefList: [],
                selected: [],
                userTableList: [],
                dialogAdd: {
                    title: "添加用户信息表",
                    open: false
                },
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    keyword: null,
                    roleKey: null,
                },
            };
        },
        watch: {
        },
        created() {
            this.initFormDef();
            this.getList();
            listRole({pageNum: 1, pageSize: 99999}).then(
                response => {
                    this.roleOptions = response.rows;
                }
            );
        },
        methods: {
            /** 查询数据 */
            getList() {
                this.loading = true;
                getUserTableSettings(this.queryParams).then(response => {
                        this.dataList = response.rows;
                        this.total = response.total;
                        this.loading = false;
                    }
                );
            },
            // 取消按钮
            cancel() {
                this.dialog.open = false;
                this.dialogAdd.open = false;
                this.reset();
            },
            cancelAdd() {
                this.dialogAdd.open = false;
                this.getList();
            },
            // 表单重置
            reset() {
                this.dialog.form = {
                    formDefName: undefined,
                    roleKeys: undefined,
                    oneToMore: false,
                    remark: undefined,
                };
                this.resetForm("dialog.form");
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.page = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.resetForm("queryForm");
                this.handleQuery();
            },
            /** 修改按钮操作 */
            handleUpdate(row) {
                this.reset();
                getUserTableSettingByKey(row.formDefKey).then(response => {
                    this.dialog.form = response.data;
                    this.dialog.title = "编辑表信息";
                    this.dialog.open = true;
                });
            },
            handleAddTable() {
                this.dialogAdd.open = true;
            },
            initFormDef() {
                listDef({pageNum: 1, pageSize: 99999}).then(res => {
                    if(!res || !res.success) {
                        this.$message.warning("暂无可用表");
                        return;
                    }
                    this.formDefList = res.rows;
                    getUserTableSettings({pageNum: 1, pageSize: 99999}).then(response => {
                        this.userTableList = response.rows;
                        this.selected = []
                        if(this.userTableList && this.userTableList.length>0) {
                            this.userTableList.forEach(t => {
                                //先禁止删除
                                this.formDefList.forEach(formDef => {
                                    formDef.disabled=formDef.disabled || (formDef.formKey==t.formDefKey);
                                })
                                this.selected.push(t.formDefKey);
                            })
                        }
                    });
                });
            },
            handleChange(currentVal, forward, selectVal) {
                if('left'==forward){//向左表示删除
                    deleteUserTableSetting(selectVal.toString());
                }else if('right'==forward){//向右表示增加
                    let arr = [];
                    selectVal.forEach(item => {
                        this.formDefList.forEach(formDef => {
                            if(formDef.formKey==item) {
                                arr.push({
                                    formDefKey: formDef.formKey,
                                    formDefName: formDef.formTitle,
                                    oneToMore: false,//默认不是一对多
                                });
                            }
                        })
                    });
                    saveUserTableSetting(arr)
                }
            },
            /** 提交按钮 */
            submitForm: function() {
                this.$refs["dialog.form"].validate(valid => {
                    if (valid) {
                        if (this.dialog.form.createTime) {
                            updateUserTableSetting(this.dialog.form.id, this.dialog.form).then(response => {
                                this.msgSuccess("修改成功");
                                this.dialog.open = false;
                                this.getList();
                            });
                        } else {
                            saveUserTableSetting(this.dialog.form).then(response => {
                                this.msgSuccess("新增成功");
                                this.dialog.open = false;
                                this.getList();
                            });
                        }
                    }
                });
            },
            /** 删除按钮操作 */
            handleDelete(row) {
                this.$confirm('是否确认删除"' + row.formDefName + '"?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function() {
                    return deleteUserTableSetting(row.formDefKey);
                }).then(() => {
                    this.getList();
                    this.msgSuccess("删除成功");
                })
            },
            /** 预览表单 */
            handleDesign(row) {
                this.$router.push({ path: "/openform/reviewByKey/def/"+(row.formDefKey) });
            },
        }
    };
</script>
<style>
</style>
